package com.janson.ShiroConfig;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.janson.entity.User;
import com.janson.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Author Janson
 * @Date 2022/4/5 16:30
 * @Version 1.0
 */
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行力=>授权操作");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //info.addStringPermission("user:update");
        //拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User)subject.getPrincipal();
        //授予权限
        info.addStringPermission(currentUser.getPerms());
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行力=>认证操作");
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        String username = "root";
        String password ="123456";

        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", userToken.getUsername()));

        if (user == null){
            //会抛出异常
            return null;
        }
        //下边第一个写 user，才能在其他地方获取到当前的 用户数据，如果 不写，其他地方获取的 则为 null
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
